package com.tyqx.hashchainbackend.controller;


import com.tyqx.hashchainbackend.service.TrackUserService;
import com.tyqx.hashchainbean.module.TrackUser;
import com.tyqx.hashchainutil.common.*;
import hashchainutil.common.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Controller
@RequestMapping("/user")
public class TrackUserPicController {
    Logger logger = Logger.getLogger(this.getClass());

    @Resource
    TrackUserService trackUserService;

    @Resource
    ValidationUtil validationUtil;

    private static final String CATALOGUES = "/user/";

    @ApiOperation(value = "修改用户头像", httpMethod = "POST",
            produces = "application/json"
            , response = Dto.class,
            notes = "修改用户头像，服务器需要获取客户端header中的token串、用户上传的头像  \n" +
                    "错误码:  \n" +
                    "100000:Token已失效  \n" +
                    "100001:修改信息异常  \n" +
                    "100002:上传文件大于1M  \n" +
                    "100003:上传文件格式不正确  \n" +
                    "100004:上传文件失败  \n" +
                    "100005:上传文件不能为空！" +
                    "成功后返回结果为图片相对路径：  \n" +
                    "{  \n" +
                    "  \"data\": {  \n" +
                    "    \"userPic\": \"/user/kaixin_ffad0db0-9835-42c9-8f28-d4776f77d980.jpg\"  \n" +
                    "  },  \n" +
                    "  \"errorCode\": \"0\",  \n" +
                    "  \"msg\": \"修改成功\",  \n" +
                    "  \"success\": \"true\"  \n" +
                    "}")
    @RequestMapping(value = "/modifyUserInfo",
            method = RequestMethod.POST,
            produces = "application/json")
    //指定参数说明
    @ApiImplicitParam(required = true, value = "唯一凭证",
            name = "token", paramType = "header")
    @ResponseBody
    public Dto modifyUserInfo(@ApiParam(value = "上传的文件")
                              @RequestParam(value = "userPic", required = false)
                                      MultipartFile file,
                              HttpServletRequest request) {
        String token = request.getHeader("token");
        TrackUser user = validationUtil.getUser(token);
        if (null == user)
            return DtoUtil.returnFail("Token已失效", "100000");
        String userPic = "";
        if (EmptyUtils.isNotEmpty(file)) {
            String path = PropertiesUtils.get("public.properties", "picUpPath");
            //原文件名
            String oldFileName = file.getOriginalFilename();
            // 上传文件大小(1M)
            int fileSize = 1024 * 1000;
            // 原文件后缀
            String prefix = FilenameUtils.getExtension(oldFileName);
            if (file.getSize() > fileSize) {
                logger.debug("上传文件大于1M,错误码：100002");
                return DtoUtil.returnFail("上传文件大于1M", "100002");
            } else if (prefix.equalsIgnoreCase("jpg")
                    || prefix.equalsIgnoreCase("jpeg")
                    || prefix.equalsIgnoreCase("bmp")
                    || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("gif")) {
                String fileName = "kaixin_" + UUID.randomUUID() + "." + prefix;
                File targetFile = new File(path + CATALOGUES, fileName);
                // 保存
                try {
                    //File oldFile = new File(path +File.separator+ user.getAvatarPath());
                   /* if (oldFile.exists()) {
                        oldFile.delete();
                    }*/
                    if (!targetFile.getParentFile().exists())
                        targetFile.getParentFile().mkdirs();
                    file.transferTo(targetFile);
                } catch (IOException e) {
                    logger.debug("上传文件失败,错误码：100004");
                    e.printStackTrace();
                    return DtoUtil.returnFail("上传文件失败", "100004");
                }

                userPic = CATALOGUES + fileName;
            } else {
                logger.debug("上传文件格式不正确，上传格式为" + prefix + ",错误码：100003");
                return DtoUtil.returnFail("上传文件格式不正确，上传格式为" + prefix, "100003");
            }
        } else {
            logger.debug("上传文件不能为空,错误码：100005");
            return DtoUtil.returnFail("上传文件不能为空", "100005");
        }
        //user.setAvatarPath(userPic);
        try {
            if (trackUserService.getUserModify(user)>0) {
                logger.debug("修改头像成功，头像路径为：" + userPic);
                return DtoUtil.returnSuccess("修改成功", userPic);
            }
            logger.debug("修改信息异常,错误码：100004");
            return DtoUtil.returnFail("修改信息异常", "100001");
        } catch (Exception e) {
            logger.debug("修改信息异常,错误码：100004");
            e.printStackTrace();
            return DtoUtil.returnFail("修改信息异常", "100001");
        }
    }


    @RequestMapping(value = "/uploadImpage",
            method = RequestMethod.POST,
            produces = "application/json")
    @ResponseBody
    public Map<String,Object> uploadImpage(@ApiParam(value = "上传的文件")
                              @RequestParam(value = "file", required = false)
                                      MultipartFile file,
                            HttpServletRequest request) {
        Map<String,Object> map=new HashMap<>();
        Subject currentUser = SecurityUtils.getSubject();
        TrackUser currUser=(TrackUser) currentUser.getSession().getAttribute("trackUser");
        String userName=currUser.getUserName()+"/";
        String userPic = "";
        if (EmptyUtils.isNotEmpty(file)) {
            String path = PropertiesUtils.get("public.properties", "picUpPath");
            //原文件名
            String oldFileName = file.getOriginalFilename();
            // 上传文件大小(1M)
            int fileSize = 1024 * 1000;
            // 原文件后缀
            String prefix = FilenameUtils.getExtension(oldFileName);
            if (file.getSize() > fileSize) {
                logger.debug("上传文件大于1M,错误码：100002");
            } else if (prefix.equalsIgnoreCase("jpg")
                    || prefix.equalsIgnoreCase("jpeg")
                    || prefix.equalsIgnoreCase("bmp")
                    || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("gif")) {
                String fileName = "jzt_" + UUID.randomUUID() + "." + prefix;
                File targetFile = new File(path + CATALOGUES+userName, fileName);
                // 保存
                try {
                    /*File oldFile = new File(currUser.getAvatarPath());
                    if (oldFile.exists()) {
                        oldFile.delete();
                    }*/
                    if (!targetFile.getParentFile().exists())
                        targetFile.getParentFile().mkdirs();
                    file.transferTo(targetFile);
                } catch (IOException e) {
                    logger.debug("上传文件失败,错误码：100004");
                    e.printStackTrace();
                }

                userPic = CATALOGUES + userName + fileName;
            } else {
                logger.debug("上传文件格式不正确，上传格式为" + prefix + ",错误码：100003");
            }
        } else {
            logger.debug("上传文件不能为空,错误码：100005");
        }
        map.put("userPic",userPic);
        return map;
    }
}
